<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="false"
      :onRowSelectChange="selectChange"
      columnsRef="jzySeries"
      :onColumnsChange="columns => (this.columns = columns)"
    >
      <!--      <template slot="controls" slot-scope="props">-->
      <!--        <el-button size="small" type="primary" icon="el-icon-plus" @click="openimportPjDialog()">导入配件</el-button>-->
      <!--&lt;!&ndash;        <el-button size="small" type="primary" @click="downloadTemplate">下载导入模板</el-button>&ndash;&gt;-->
      <!--&lt;!&ndash;        <el-button size="small" type="primary" @click="importPrice">导入</el-button>&ndash;&gt;-->
      <!--      </template>-->
    </FilterTable>

    <!-- 编辑窗口 -->
    <Drawer :visible.sync="visibleDrawer" :title="title" :width="920" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <part-info v-model="initData" :type="handleType" :rowData="formData" @close="infoClose" />
    </Drawer>

    <BaseDialog
      style="min-height: 80vh;"
      :visible.sync="visibleImportPeij"
      width="80vw"
      title="配件导入"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <UploadExcel ref="import" template-file-name="配件价格导入模板.xlsx" :importRules="importRules" :onComplete="importComplete" @close="visibleImportPeij = false" />
    </BaseDialog>
    <!--    :onBeforeDownloadTemp="setParts"-->
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { getpartinfo, importPartPrice, selectCategories } from '@/api/partsmanage/partinfos/partInfoManage/index';
import { getCurrentUser } from '@/api/cms-api/origin/construct/dealer';
import partInfo from './partInfo';
import { dateFormat } from '@/utils';

export default {
  name: 'partInfoManageDealer',
  components: { partInfo },
  mixins: [dictionary],
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchApi: getpartinfo,
      fetchParams: { xhrAbort: true },
      visibleDrawer: false,
      visibleImportPeij: false,
      handleType: '',
      formData: {},
      title: '',
      initData: {},
      partinfos: {},
      rowSelectData: [],
      importRules: [
        { prop: 'bjpjsx', title: '配件属性', rule: [{ required: true, message: '配件属性不能为空' }, { itemList: this.createDictList('5000') }] },
        { prop: 'bjxmbh', title: '配件代码', rule: { required: true, message: '配件代码不能为空' } },
        { prop: 'bjzwmc', title: '配件名称' },
        {
          prop: 'ls',
          title: '终端建议零售VIP价格',
          rule: [
            // { required: true, message: '终端建议零售VIP价格不能为空' },
            { pattern: /^\d+(\.)?(\d)?(\d)?$/, message: '请输入正确的终端建议零售VIP价格' }
          ]
        },
        {
          prop: 'bx',
          title: '终端建议零售价格格',
          rule: [
            // { required: true, message: '终端建议零售价格格不能为空' },
            { pattern: /^\d+(\.)?(\d)?(\d)?$/, message: '请输入正确的终端建议零售价格格' }
          ]
        },
        {
          prop: 'xtyxrq',
          title: '有效日期',
          rule: [
            { required: true, message: '有效日期不能为空' },
            {
              validator: (callback, rule, val, row) => {
                try {
                  const date = new Date(val);
                  if (date.toDateString() !== 'Invalid Date') {
                    row.xtyxrq = dateFormat('yyyy-MM-dd hh:mm:ss', date);
                    callback();
                  } else {
                    callback(new Error('有效日期格式不对'));
                  }
                } catch (e) {
                  callback(new Error('a有效日期格式不对'));
                }
              }
            }
          ]
        },
        {
          prop: 'xtsxrq',
          title: '失效日期',
          rule: [
            { required: true, message: '失效日期不能为空' },
            {
              validator: (callback, rule, val, row) => {
                try {
                  const date = new Date(val);
                  if (date.toDateString() !== 'Invalid Date') {
                    row.xtsxrq = dateFormat('yyyy-MM-dd hh:mm:ss', date);
                    callback();
                  } else {
                    callback(new Error('失效日期格式不对'));
                  }
                } catch (e) {
                  callback(new Error('失效日期格式不对'));
                }
              }
            }
          ]
        }
      ]
    };
  },
  async created() {
    this.columns.find(x => x.dataIndex === 'bjpjsx').hidden = true;
    this.columns.find(x => x.dataIndex == 'bjpjsx').dictItems = this.createDictList('5000');
    // 获取当前登录人信息
    await getCurrentUser({}).then(response => {
      console.info(response);
      if (response.data.appId === 'beijing') {
        console.info(this.topFilterList);
        this.topFilterList.find(x => x.fieldName === 'bjpjsx').hidden = false;
        this.columns.find(x => x.dataIndex === 'bjpjsx').hidden = false;
      }
    });
    await selectCategories({}).then(response => {
      console.info(response);
      this.topFilterList.find(x => x.fieldName === 'bjpjlx').itemList = response.data.map(y => ({
        text: y.bjpjlx,
        value: y.bjpjlx
      }));
    });
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT2',
          label: '配件代码',
          fieldName: 'bjxmbh'
        },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'bjzwmc'
        },
        {
          type: 'SELECT',
          label: '配件属性',
          fieldName: 'bjpjsx',
          placeholder: '请选择...',
          itemList: this.createDictList('5000'),
          hidden: true
        },
        {
          type: 'SELECT',
          label: '配件类别',
          fieldName: 'bjpjlx',
          placeholder: '请选择...',
          itemList: []
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.editHandle(props.row, 'show')}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '配件代码',
          dataIndex: 'bjxmbh',
          sorter: true
        },
        {
          title: '配件名称',
          dataIndex: 'bjzwmc',
          sorter: true
        },
        {
          title: '配件属性',
          dataIndex: 'bjpjsx',
          sorter: true
        },
        {
          title: '首用车型',
          dataIndex: 'bjsycx',
          sorter: true
        },
        // {
        //   title: '常规订货单价',
        //   dataIndex: 'xs',
        //   sorter: true,
        //   precision: 2,
        // },
        {
          title: '终端建议零售VIP价格',
          dataIndex: 'ls',
          sorter: true,
          precision: 2
        },
        {
          title: '终端建议零售价格',
          dataIndex: 'bx',
          sorter: true,
          precision: 2
        },
        {
          title: '销售索标识',
          dataIndex: 'bjdgbz',
          dictItems: [
            { text: '是', value: 'Y' },
            { text: '否', value: 'N' }
          ],
          sorter: true
        },
        {
          title: '配件类别',
          dataIndex: 'bjpjlx',
          sorter: true
        },
        {
          title: '最小订购量',
          dataIndex: 'bjcgzx',
          sorter: true
        }
      ];
    },
    selectChange(val) {
      console.log('val', val);
      this.rowSelectData = val;
    },
    editHandle(row, type) {
      if (type === 'edit') {
        this.title = '编辑';
      } else if (type === 'show') {
        this.title = '详情';
      }
      this.formData = row;
      this.handleType = type;
      this.visibleDrawer = true;
    },
    // 配件列表明细数据获取
    syncPjFun(details) {
      this.partinfos = details;
      console.info(details);
      console.info(partinfos);
    },
    downloadTemplate() {
      this.$confirm('下载模板', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          window.open('/static/tinymce/template/PartInfos.xls');
          this.$message({
            type: 'success',
            message: '下载成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    setParts(callback) {
      getpartinfo(this.fetchParams).then(res => {
        console.info(res.data.records);
        res.data.records.forEach(i => {
          i.bjpjsx = this.createDictText(i.bjpjsx, '5000');
        });
        callback(res.data.records);
      });
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    /* 打开导入配件Dialog */
    openimportPjDialog() {
      this.visibleImportPeij = true;
    },
    //导入
    async importComplete(datas, callback) {
      const errorData = [];
      console.info(datas);
      datas.forEach((item, index1) => {
        const indexarr = [];
        datas.forEach((i, index2) => {
          if (i.bjxmbh === item.bjxmbh && i.bjpjsx === item.bjpjsx && index1 !== index2) {
            indexarr.push(index2 + 1);
          }
        });
        if (indexarr.length && item.xtsxrq < item.xtyxrq) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `与第${indexarr.join(',')}行配件信息重复;失效日期不能小于有效日期`
          });
        } else if (item.xtsxrq < item.xtyxrq) {
          console.info(item.xtsxrq);
          console.info(item.xtyxrq);
          errorData.push({
            rownum: index1 + 1,
            errormsg: `失效日期不能小于有效日期`
          });
        } else if (indexarr.length) {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `与第${indexarr.join(',')}行配件信息重复`
          });
        }
        if (item.ls === '' && item.bx === '') {
          errorData.push({
            rownum: index1 + 1,
            errormsg: `零售价和终端建议零售价格不能同时为空;`
          });
        }
      });
      if (errorData.length) {
        callback(errorData);
      } else {
        importPartPrice(datas).then(res => {
          if (res.resultCode == 200) {
            if (res.data.status) {
              this.visibleImportPeij = false;
              this.$notify.success({ title: '提示信息', message: '批量导入成功' });
              callback();
              this.infoClose('refresh');
            } else {
              callback(res.data.errorData);
            }
          } else {
            callback([{ errormsg: '服务器运行异常' }]);
          }
        });
      }
    },
    infoClose(rData) {
      this.visibleDrawer = false;
      console.info(rData);
      if (rData.type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style scoped></style>
